package rules

import (
	"fmt"
	"strings"
)

// RollbackTableRelationshipRule 回滚脚本表关联检查规则
type RollbackTableRelationshipRule struct{}

// Name 规则名称
func (r *RollbackTableRelationshipRule) Name() string {
	return "回滚脚本表关联检查"
}

// Check 执行检查
func (r *RollbackTableRelationshipRule) Check(data DDLCheckData) CheckResult {
	result := CheckResult{
		Status:  StatusPassed,
		Details: make([]string, 0),
	}

	if strings.TrimSpace(data.RollbackScript) == "" {
		result.Details = append(result.Details, "⚠️ 未提供回滚脚本，跳过回滚脚本表关联检查")
		result.Status = StatusSkipped
		return result
	}

	// 检查回滚脚本是否包含正确的表关联
	expectedFormat := fmt.Sprintf("%s.%s", data.Schema, data.Table)
	if strings.Contains(data.RollbackScript, expectedFormat) {
		result.Details = append(result.Details, "✅ 回滚脚本正确使用了schema.table格式")
	} else {
		result.Details = append(result.Details, fmt.Sprintf("❌ 回滚脚本应使用%s格式引用表", expectedFormat))
		result.Status = StatusFailed
	}

	// 检查回滚脚本是否包含有效的操作
	upperScript := strings.ToUpper(data.RollbackScript)
	if strings.Contains(upperScript, "DROP") || strings.Contains(upperScript, "ALTER") {
		result.Details = append(result.Details, "✅ 回滚脚本包含有效的SQL操作语句")
	} else {
		result.Details = append(result.Details, "❌ 回滚脚本应包含DROP或ALTER语句")
		result.Status = StatusFailed
	}

	return result
}
